import {history, post, message, get} from '@/utils/utils'

const device = {
  namespaced: true,
  state: {
    list: [],
    total: 0,
    installedNum: 0,
    hasData: true,
    pageNum: 1,
    detail: {}
  },

  mutations: {
    save(state, { field, payload }) {
      if (Object.prototype.toString.call(payload) === '[object Object]') {
        state[field] = { ...state[field], ...payload }
      } else {
        state[field] = payload
      }
    }
  },

  actions: {
    getStatistics({ commit }, deviceType = '00') {
      get({
        api: `/mat/matdeviceinfo/statistical?deviceType=${deviceType}`,
        success: ({data}) => {
          const {inStorage, installed} = data

          commit('save', {field: 'total', payload: inStorage})
          commit('save', {field: 'installedNum', payload: installed})
        }
      })
    },

    getList({ commit, state }, {deviceType = '00', pageNum = 1, search = ''} = {}) {
      get({api: '/mat/matdeviceinfo/getDevicePage',
        data: {
          deviceType,
          current: pageNum,
          size: 10,
          search
        },
        success: ({data}) => {
          const {pages, records} = data
          const {list} = state
          let recordList = list

          if (pageNum > 1) {
            recordList = recordList.concat(records)
          } else {
            recordList = records || []
            commit('save', {field: 'hasData', payload: true})
          }

          if (pages === pageNum || pages === 0) commit('save', {field: 'hasData', payload: false})

          commit('save', {field: 'pageNum', payload: pageNum})
          commit('save', {field: 'list', payload: recordList})
        }})
    },

    getDetail({ commit }, uid) {
      get({
        api: `/mat/matdeviceinfo/${uid}`,
        success: ({data}) => {
          commit('save', {field: 'detail', payload: data})
        }
      })
    }
  }
}

export default device
